
package com.lyn.serialPort;

import android.util.Log;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.Iterator;

public class SerialPortFinder {
    private static final String TAG = SerialPortFinder.class.getSimpleName();
    private static final String DRIVERS_PATH = "/proc/tty/drivers";
    private static final String SERIAL_FIELD = "serial";

    public SerialPortFinder() {
        File file = new File("/proc/tty/drivers");
        boolean b = file.canRead();
        Log.i(TAG, "SerialPortFinder: file.canRead() = " + b);
    }

    private ArrayList<Driver> getDrivers() throws IOException {
        ArrayList<Driver> drivers = new ArrayList();
        LineNumberReader lineNumberReader = new LineNumberReader(new FileReader("/proc/tty/drivers"));

        String readLine;
        while ((readLine = lineNumberReader.readLine()) != null) {
            String driverName = readLine.substring(0, 21).trim();
            String[] fields = readLine.split(" +");
            if (fields.length >= 5 && fields[fields.length - 1].equals("serial")) {
                Log.d(TAG, "Found new driver " + driverName + " on " + fields[fields.length - 4]);
                drivers.add(new Driver(driverName, fields[fields.length - 4]));
            }
        }

        return drivers;
    }

    public ArrayList<Device> getDevices() {
        ArrayList devices = new ArrayList();

        try {
            ArrayList<Driver> drivers = this.getDrivers();
            Iterator var3 = drivers.iterator();

            while (var3.hasNext()) {
                Driver driver = (Driver) var3.next();
                String driverName = driver.getName();
                ArrayList<File> driverDevices = driver.getDevices();
                Iterator var7 = driverDevices.iterator();

                while (var7.hasNext()) {
                    File file = (File) var7.next();
                    String devicesName = file.getName();
                    devices.add(new Device(devicesName, driverName, file));
                }
            }
        } catch (IOException var10) {
            var10.printStackTrace();
        }

        return devices;
    }

    public Device getDevice(String name) {
        ArrayList<Device> devices = getDevices();
        for (Device device : devices) {
            if (device.getName().equals(name)) {
                return device;
            }
        }
        return null;
    }
}
